package pri.hillchen.springbootstd.bms.controller.system;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pri.hillchen.springbootstd.bms.common.util.ValidateCode;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hillchen on 2017/10/14.
 */
@Controller
public class LoginController {
    @RequestMapping("/")
    public String home(){
        return index();
    }
    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/logout")
    public String logout(){
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return login();
    }

    @RequestMapping("/jwtLogin")
    public  Map<String,Object> jwtLogin(String userName, String password){
        return loginHandle(userName,password);
    }

    @RequestMapping("/checkLogin")
    @ResponseBody
    public Map<String,Object> checkLogin(String userName, String password){
        return loginHandle(userName,password);
    }

    private  Map<String,Object> loginHandle(String userName, String password){
        Map<String,Object> ret = new HashMap<String,Object>();
        String msg = "";
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        token.setRememberMe(true);
        Subject subject = SecurityUtils.getSubject();
        ret.put("succ",false);
        try {
            subject.login(token);
            if (subject.isAuthenticated()) {
                ret.put("succ",true);
            } else {
                ret.put("succ",false);
            }
        } catch (IncorrectCredentialsException e) {
            msg = "登录密码错误.";
        } catch (ExcessiveAttemptsException e) {
            msg = "登录失败次数过多";
        } catch (LockedAccountException e) {
            msg = "帐号已被锁定. ";
            ret.put("message", msg);
        } catch (DisabledAccountException e) {
            msg = "帐号已被禁用.";
        } catch (ExpiredCredentialsException e) {
            msg = "帐号已过期.";
        } catch (UnknownAccountException e) {
            msg = "帐号不存在.";
        } catch (UnauthorizedException e) {
            msg = "您没有得到相应的授权！" + e.getMessage();
        }
        ret.put("message", msg);
        return ret;
    }

    @RequestMapping("/validateCode/getCode")
    public void  getValidateCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int width = 67;
        int height = 37;
        int codeCount = 4;
        //设置response头信息
        //禁止缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        ValidateCode.CodeInfo codeInfo = ValidateCode.createValidateCode(new ValidateCode.CodeBuilder()
            .setCodeCount(codeCount).setImgWidth(width).setImgHeight(height)
        );

        request.getSession().setAttribute("validateCode", String.valueOf(codeInfo.getCodeChars()));

        ImageIO.write(codeInfo.getBufferedImage(),
                "JPEG", response.getOutputStream());
        response.getOutputStream().flush();
    }

    @RequestMapping("/validateCode/validate")
    @ResponseBody
    public boolean  validateCode(HttpServletRequest request,String validateCode){
        Object sessionValidateCode = request.getSession().getAttribute("validateCode");
        return sessionValidateCode != null && sessionValidateCode.toString().equalsIgnoreCase(validateCode);
    }
}
